package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBHelper {

	private static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String JDBC_URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
	private static final String JDBC_USERNAME = "lizhi";
	private static final String JDBC_PWD = "lizhi";

	
	private Connection conn = null;
	private PreparedStatement stm = null;
	
	
	public DBHelper(){
		try {
			Class.forName(JDBC_DRIVER);
			conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME,JDBC_PWD);
			conn.setAutoCommit(false);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("数据库初始化失败");
		}
	}
	
	public Connection getConn(){
		return conn;
	}
	
	public PreparedStatement makeStm(String sql) throws SQLException{
		if(stm!=null){
			stm.close();
		}
		stm = conn.prepareStatement(sql);
		return stm;
	}
	
	public void setParam(int index, Object obj) throws SQLException{
		stm.setObject(index, obj);
	}
	
	public ResultSet executeQuery() throws SQLException{
		return stm.executeQuery();
	}
	
//	public void closeStmt() throws SQLException{
//		stm.close();
//	}

	public int executeUpdate() throws SQLException {
		// TODO Auto-generated method stub
		return stm.executeUpdate();
	}

	public void commit() throws SQLException {
		conn.commit();
	}

	public void rollback() {
		try {
			conn.rollback();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			throw new RuntimeException("数据库回滚失败");
		}		
	}

	public void closeAll() {
		try {
			if(stm!=null)
				stm.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if(conn!=null)
				conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
}
